import React, { useState, useEffect } from 'react';
import { 
  Tree, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message, 
  Space, 
  Card, 
  Row, 
  Col, 
  Statistic,
  Tag,
  Tooltip,
  Popconfirm,
  Divider,
  Alert,
  Typography,
  Badge,
  Collapse
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  FolderOutlined,
  FileOutlined,
  SettingOutlined,
  CopyOutlined,
  DragOutlined,
  BranchesOutlined,
  ApartmentOutlined,
  ClusterOutlined,
  NodeIndexOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Paragraph } = Typography;
const { Panel } = Collapse;

const FactorTree = () => {
  const [treeData, setTreeData] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingNode, setEditingNode] = useState(null);
  const [form] = Form.useForm();
  const [selectedNode, setSelectedNode] = useState(null);

  // 模拟因子树数据
  const mockTreeData = [
    {
      key: '0-0',
      title: '选基因子',
      type: 'category',
      description: '用于基金筛选的因子集合',
      businessScenario: '基金筛选',
      factorCount: 15,
      children: [
        {
          key: '0-0-0',
          title: '收益因子',
          type: 'subcategory',
          description: '基金收益相关因子',
          businessScenario: '基金筛选',
          factorCount: 5,
          children: [
            {
              key: '0-0-0-0',
              title: '动量因子',
              type: 'factor',
              description: '基于价格动量的技术分析因子',
              businessScenario: '基金筛选',
              dataSource: 'Wind',
              formula: 'momentum = (price_t - price_t-20) / price_t-20'
            },
            {
              key: '0-0-0-1',
              title: '价值因子',
              type: 'factor',
              description: '基于估值指标的基本面因子',
              businessScenario: '基金筛选',
              dataSource: 'Choice',
              formula: 'value = (book_value / market_value)'
            }
          ]
        },
        {
          key: '0-0-1',
          title: '风险因子',
          type: 'subcategory',
          description: '基金风险相关因子',
          businessScenario: '基金筛选',
          factorCount: 4,
          children: [
            {
              key: '0-0-1-0',
              title: '波动率因子',
              type: 'factor',
              description: '基于历史波动率的风险因子',
              businessScenario: '基金筛选',
              dataSource: 'Wind',
              formula: 'volatility = std(returns_60d)'
            },
            {
              key: '0-0-1-1',
              title: 'Beta因子',
              type: 'factor',
              description: '基于市场敏感性的风险因子',
              businessScenario: '基金筛选',
              dataSource: 'Wind',
              formula: 'beta = cov(returns, market_returns) / var(market_returns)'
            }
          ]
        }
      ]
    },
    {
      key: '0-1',
      title: '量化投研因子',
      type: 'category',
      description: '用于量化投资研究的因子集合',
      businessScenario: '量化投研',
      factorCount: 12,
      children: [
        {
          key: '0-1-0',
          title: '技术因子',
          type: 'subcategory',
          description: '技术分析相关因子',
          businessScenario: '量化投研',
          factorCount: 6,
          children: [
            {
              key: '0-1-0-0',
              title: '流动性因子',
              type: 'factor',
              description: '基于交易流动性的技术因子',
              businessScenario: '量化投研',
              dataSource: 'Wind',
              formula: 'liquidity = log(turnover_rate * avg_volume)'
            }
          ]
        },
        {
          key: '0-1-1',
          title: '基本面因子',
          type: 'subcategory',
          description: '基本面分析相关因子',
          businessScenario: '量化投研',
          factorCount: 6,
          children: [
            {
              key: '0-1-1-0',
              title: '质量因子',
              type: 'factor',
              description: '基于公司盈利质量的基本面因子',
              businessScenario: '量化投研',
              dataSource: 'Choice',
              formula: 'quality = (roe * 0.4 + debt_to_equity * 0.3 + asset_turnover * 0.3)'
            },
            {
              key: '0-1-1-1',
              title: '成长因子',
              type: 'factor',
              description: '基于公司成长性的基本面因子',
              businessScenario: '量化投研',
              dataSource: 'Choice',
              formula: 'growth = (revenue_growth * 0.5 + earnings_growth * 0.5)'
            }
          ]
        }
      ]
    },
    {
      key: '0-2',
      title: '特色数据输出',
      type: 'category',
      description: '特色数据分析和输出因子',
      businessScenario: '特色数据',
      factorCount: 8,
      children: [
        {
          key: '0-2-0',
          title: '另类因子',
          type: 'subcategory',
          description: '另类数据相关因子',
          businessScenario: '特色数据',
          factorCount: 4,
          children: [
            {
              key: '0-2-0-0',
              title: 'ESG因子',
              type: 'factor',
              description: '环境、社会和治理因子',
              businessScenario: '特色数据',
              dataSource: 'Bloomberg',
              formula: 'esg = (environmental_score * 0.4 + social_score * 0.3 + governance_score * 0.3)'
            }
          ]
        }
      ]
    }
  ];

  // 业务场景选项
  const businessScenarios = ['基金筛选', '量化投研', '特色数据', '风险管理', '资产配置'];
  const nodeTypes = ['category', 'subcategory', 'factor'];

  useEffect(() => {
    const stored = localStorage.getItem('factorTreeData');
    if (stored) {
      setTreeData(JSON.parse(stored));
    } else {
      setTreeData(mockTreeData);
    }
    setExpandedKeys(['0-0', '0-1', '0-2']);
  }, []);

  // 递归查找节点
  const findNode = (nodes, key) => {
    for (let node of nodes) {
      if (node.key === key) return node;
      if (node.children) {
        const found = findNode(node.children, key);
        if (found) return found;
      }
    }
    return null;
  };

  // 递归更新节点
  const updateNode = (nodes, key, updates) => {
    return nodes.map(node => {
      if (node.key === key) {
        return { ...node, ...updates };
      }
      if (node.children) {
        return { ...node, children: updateNode(node.children, key, updates) };
      }
      return node;
    });
  };

  // 递归删除节点
  const deleteNode = (nodes, key) => {
    return nodes.filter(node => {
      if (node.key === key) return false;
      if (node.children) {
        node.children = deleteNode(node.children, key);
      }
      return true;
    });
  };

  // 递归添加节点
  const addNode = (nodes, parentKey, newNode) => {
    return nodes.map(node => {
      if (node.key === parentKey) {
        return {
          ...node,
          children: node.children ? [...node.children, newNode] : [newNode]
        };
      }
      if (node.children) {
        return { ...node, children: addNode(node.children, parentKey, newNode) };
      }
      return node;
    });
  };

  const handleAdd = (parentKey = null) => {
    setEditingNode(null);
    form.resetFields();
    if (parentKey) {
      form.setFieldsValue({ parentKey });
    }
    setIsModalVisible(true);
  };

  const handleEdit = (node) => {
    setEditingNode(node);
    form.setFieldsValue({
      title: node.title,
      type: node.type,
      description: node.description,
      businessScenario: node.businessScenario,
      dataSource: node.dataSource,
      formula: node.formula
    });
    setIsModalVisible(true);
  };

  const handleDelete = (key) => {
    const node = findNode(treeData, key);
    if (node.children && node.children.length > 0) {
      message.warning('该节点包含子节点，请先删除子节点');
      return;
    }
    const newTree = deleteNode(treeData, key);
    setTreeData(newTree);
    localStorage.setItem('factorTreeData', JSON.stringify(newTree));
    message.success('删除成功');
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingNode) {
        // 编辑模式
        const updatedTree = updateNode(treeData, editingNode.key, values);
        setTreeData(updatedTree);
        localStorage.setItem('factorTreeData', JSON.stringify(updatedTree));
        message.success('更新成功');
      } else {
        // 新增模式
        const newNode = {
          key: `${Date.now()}`,
          title: values.title,
          type: values.type,
          description: values.description,
          businessScenario: values.businessScenario,
          dataSource: values.dataSource,
          formula: values.formula,
          factorCount: values.type === 'factor' ? 1 : 0
        };

        if (values.parentKey) {
          // 添加到指定父节点
          const updatedTree = addNode(treeData, values.parentKey, newNode);
          setTreeData(updatedTree);
          localStorage.setItem('factorTreeData', JSON.stringify(updatedTree));
        } else {
          // 添加到根节点
          const newTree = [...treeData, newNode];
          setTreeData(newTree);
          localStorage.setItem('factorTreeData', JSON.stringify(newTree));
        }
        message.success('添加成功');
      }
      
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  const handleSelect = (selectedKeys, info) => {
    setSelectedKeys(selectedKeys);
    if (selectedKeys.length > 0) {
      const node = findNode(treeData, selectedKeys[0]);
      setSelectedNode(node);
    } else {
      setSelectedNode(null);
    }
  };

  const handleExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys);
  };

  const renderTitle = (node) => {
    const getIcon = () => {
      switch (node.type) {
        case 'category':
          return <ClusterOutlined style={{ color: '#1890ff', fontSize: '16px' }} />;
        case 'subcategory':
          return <ApartmentOutlined style={{ color: '#52c41a', fontSize: '14px' }} />;
        case 'factor':
          return <NodeIndexOutlined style={{ color: '#faad14', fontSize: '12px' }} />;
        default:
          return <FileOutlined />;
      }
    };

    const getNodeStyle = () => {
      switch (node.type) {
        case 'category':
          return { 
            fontWeight: 'bold', 
            fontSize: '16px',
            color: '#1890ff',
            padding: '8px 12px',
            borderRadius: '6px',
            backgroundColor: '#f0f8ff',
            border: '1px solid #d6e4ff'
          };
        case 'subcategory':
          return { 
            fontWeight: '600', 
            fontSize: '14px',
            color: '#52c41a',
            padding: '6px 10px',
            borderRadius: '4px',
            backgroundColor: '#f6ffed',
            border: '1px solid #b7eb8f'
          };
        case 'factor':
          return { 
            fontSize: '13px',
            color: '#666',
            padding: '4px 8px',
            borderRadius: '3px',
            backgroundColor: '#fff7e6',
            border: '1px solid #ffd591'
          };
        default:
          return {};
      }
    };

    return (
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'space-between', 
        width: '100%',
        ...getNodeStyle()
      }}>
        <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
          {getIcon()}
          <span style={{ marginLeft: '8px' }}>{node.title}</span>
          {node.type === 'factor' && (
            <Tag color="blue" size="small" style={{ marginLeft: '8px' }}>
              {node.dataSource}
            </Tag>
          )}
          {node.type !== 'factor' && (
            <Badge 
              count={node.factorCount} 
              size="small" 
              style={{ marginLeft: '8px' }}
              color={node.type === 'category' ? '#1890ff' : '#52c41a'}
            />
          )}
        </div>
        <Space size="small" style={{ marginLeft: '16px' }}>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              size="small" 
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleEdit(node);
              }}
            />
          </Tooltip>
          <Tooltip title="添加子节点">
            <Button 
              type="text" 
              size="small" 
              icon={<PlusOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleAdd(node.key);
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个节点吗？"
            onConfirm={(e) => {
              e.stopPropagation();
              handleDelete(node.key);
            }}
            onCancel={(e) => e.stopPropagation()}
          >
            <Button 
              type="text" 
              size="small" 
              danger
              icon={<DeleteOutlined />}
              onClick={(e) => e.stopPropagation()}
            />
          </Popconfirm>
        </Space>
      </div>
    );
  };

  const getNodeStats = () => {
    let totalCategories = 0;
    let totalSubcategories = 0;
    let totalFactors = 0;

    const countNodes = (nodes) => {
      nodes.forEach(node => {
        if (node.type === 'category') totalCategories++;
        else if (node.type === 'subcategory') totalSubcategories++;
        else if (node.type === 'factor') totalFactors++;

        if (node.children) {
          countNodes(node.children);
        }
      });
    };

    countNodes(treeData);
    return { totalCategories, totalSubcategories, totalFactors };
  };

  const stats = getNodeStats();

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      {/* 统计信息 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
            <Statistic 
              title="总分类数" 
              value={stats.totalCategories} 
              prefix={<ClusterOutlined style={{ color: '#1890ff' }} />} 
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
            <Statistic 
              title="子分类数" 
              value={stats.totalSubcategories} 
              prefix={<ApartmentOutlined style={{ color: '#52c41a' }} />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
            <Statistic 
              title="因子数" 
              value={stats.totalFactors} 
              prefix={<NodeIndexOutlined style={{ color: '#faad14' }} />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card style={{ borderRadius: '12px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
            <Statistic 
              title="业务场景" 
              value={new Set(treeData.map(node => node.businessScenario)).size} 
              prefix={<SettingOutlined style={{ color: '#722ed1' }} />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={24}>
        {/* 左侧：因子树 */}
        <Col span={16}>
          <Card 
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <BranchesOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
                <span>因子树结构</span>
              </div>
            }
            style={{ 
              borderRadius: '12px', 
              boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
              border: '1px solid #e8e8e8'
            }}
            extra={
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={() => handleAdd()}
                style={{ borderRadius: '6px' }}
              >
                新增根分类
              </Button>
            }
          >
            <div style={{ 
              backgroundColor: '#fafafa', 
              padding: '16px', 
              borderRadius: '8px',
              border: '1px solid #e8e8e8'
            }}>
              <Tree
                treeData={treeData}
                selectedKeys={selectedKeys}
                expandedKeys={expandedKeys}
                onSelect={handleSelect}
                onExpand={handleExpand}
                titleRender={renderTitle}
                showLine={{ showLeafIcon: false }}
                showIcon={false}
                blockNode
                style={{ 
                  fontSize: '14px',
                  lineHeight: '1.6'
                }}
              />
            </div>
          </Card>
        </Col>

        {/* 右侧：节点详情 */}
        <Col span={8}>
          <Card 
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <FileOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
                <span>节点详情</span>
              </div>
            }
            style={{ 
              borderRadius: '12px', 
              boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
              border: '1px solid #e8e8e8'
            }}
          >
            {selectedNode ? (
              <div>
                <div style={{ 
                  padding: '16px', 
                  backgroundColor: '#f6ffed', 
                  borderRadius: '8px',
                  marginBottom: '16px',
                  border: '1px solid #b7eb8f'
                }}>
                  <h4 style={{ margin: '0 0 8px 0', color: '#52c41a' }}>
                    {selectedNode.title}
                  </h4>
                  <p style={{ margin: 0, color: '#666' }}>
                    {selectedNode.description}
                  </p>
                </div>

                <Collapse 
                  defaultActiveKey={['1']} 
                  size="small"
                  style={{ backgroundColor: 'transparent' }}
                >
                  <Panel header="基本信息" key="1">
                    <div style={{ fontSize: '13px', lineHeight: '1.8' }}>
                      <p><strong>节点类型：</strong>
                        <Tag color={
                          selectedNode.type === 'category' ? 'blue' : 
                          selectedNode.type === 'subcategory' ? 'green' : 'orange'
                        } style={{ marginLeft: '8px' }}>
                          {selectedNode.type === 'category' ? '分类' : 
                           selectedNode.type === 'subcategory' ? '子分类' : '因子'}
                        </Tag>
                      </p>
                      <p><strong>业务场景：</strong>{selectedNode.businessScenario}</p>
                      {selectedNode.type !== 'factor' && (
                        <p><strong>因子数量：</strong>{selectedNode.factorCount}</p>
                      )}
                      {selectedNode.type === 'factor' && (
                        <>
                          <p><strong>数据源：</strong>{selectedNode.dataSource}</p>
                          <p><strong>计算公式：</strong></p>
                          <pre style={{ 
                            background: '#f5f5f5', 
                            padding: '8px', 
                            borderRadius: '4px', 
                            fontSize: '12px',
                            margin: '8px 0 0 0'
                          }}>
                            {selectedNode.formula}
                          </pre>
                        </>
                      )}
                    </div>
                  </Panel>
                </Collapse>
              </div>
            ) : (
              <div style={{ 
                textAlign: 'center', 
                padding: '40px 20px', 
                color: '#999',
                fontSize: '14px'
              }}>
                <BranchesOutlined style={{ fontSize: '48px', marginBottom: '16px', color: '#d9d9d9' }} />
                <p>请选择一个节点查看详情</p>
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 新增/编辑节点模态框 */}
      <Modal
        title={editingNode ? '编辑节点' : '新增节点'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ type: 'category' }}
        >
          <Form.Item
            name="title"
            label="节点名称"
            rules={[{ required: true, message: '请输入节点名称' }]}
          >
            <Input placeholder="请输入节点名称" />
          </Form.Item>

          <Form.Item
            name="type"
            label="节点类型"
            rules={[{ required: true, message: '请选择节点类型' }]}
          >
            <Select placeholder="请选择节点类型">
              {nodeTypes.map(type => (
                <Option key={type} value={type}>
                  {type === 'category' ? '分类' : 
                   type === 'subcategory' ? '子分类' : '因子'}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="businessScenario"
            label="业务场景"
            rules={[{ required: true, message: '请选择业务场景' }]}
          >
            <Select placeholder="请选择业务场景">
              {businessScenarios.map(scenario => (
                <Option key={scenario} value={scenario}>{scenario}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea 
              rows={3}
              placeholder="请输入节点描述"
            />
          </Form.Item>

          <Form.Item
            name="dataSource"
            label="数据源"
            rules={form.getFieldValue('type') === 'factor' ? 
              [{ required: true, message: '请选择数据源' }] : []
            }
          >
            <Select placeholder="请选择数据源" disabled={form.getFieldValue('type') !== 'factor'}>
              <Option value="Wind">Wind</Option>
              <Option value="Choice">Choice</Option>
              <Option value="Bloomberg">Bloomberg</Option>
              <Option value="Reuters">Reuters</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="formula"
            label="计算公式"
            rules={form.getFieldValue('type') === 'factor' ? 
              [{ required: true, message: '请输入计算公式' }] : []
            }
          >
            <TextArea 
              rows={4}
              placeholder="请输入计算公式"
              disabled={form.getFieldValue('type') !== 'factor'}
            />
          </Form.Item>

          <Form.Item name="parentKey" hidden>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default FactorTree; 